﻿using Castle.Core.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yto.Common;
using Yto.Common.io;
using Yto.Common.Dependency;
using Yto.Threading;
using Yto.Threading.BackgroundWorkers;

namespace com.ytocargo.Application.Ftp
{
    public class FTPManager : TimedBgdWorker, ISingleton
    {
        private FTPFactory fTPFactory;
        private ICtnManager _ctnManager;
        private ILogger _logger;

        public FTPManager(BaseTimer baseTimer,
            ICtnManager ctnManager)
            : base(baseTimer)
        {
            JobPeriod = int.TryParse(ConfigurationManager.AppSettings["Period"], out int tempValue)
                        ? tempValue : 5000;
            baseTimer.Period = JobPeriod;
            _ctnManager = ctnManager;
            fTPFactory = new FTPFactory();
            InitFTP();

            _logger = _ctnManager.IsRegisted<ILoggerFactory>() ?
                _ctnManager.Resolver<ILoggerFactory>().Create(typeof(FTPManager))
                : NullLogger.Instance;
        }


        private void InitFTP()
        {
            fTPFactory.setRemoteHost(ConfigurationManager.AppSettings["FTPHost"]);
            fTPFactory.setRemotePort(int.TryParse(ConfigurationManager.AppSettings["FTPPort"], out int tempValue)
                        ? tempValue : 21);
            fTPFactory.setRemoteUser(ConfigurationManager.AppSettings["FTPUser"]);
            fTPFactory.setRemotePass(ConfigurationManager.AppSettings["FTPPass"]);
            fTPFactory.setRemotePath(ConfigurationManager.AppSettings["FTPPath"]);

        }

        public int JobPeriod { get; private set; }


        protected override void DoWork()
        {
            try
            {
                var UnUpdateDir = ConfigurationManager.AppSettings["UnUpdateDir"];
                var UpdatedDir = ConfigurationManager.AppSettings["UpdatedDir"];
                if (!FileHelper.DirectoryExist(UpdatedDir))
                {
                    FileHelper.CreateDirectory(UpdatedDir);
                }
                if (FileHelper.DirectoryExist(UnUpdateDir))
                {
                    var list = FileHelper.GetAllFile(UnUpdateDir);

                    foreach (var item in list)
                    {
                        string fileName = item.FullName;
                        fTPFactory.upload(fileName);

                        FileHelper.Move2Path(fileName, UpdatedDir, true);

                        _logger.Info($"文件{ fileName }在{ DateTime.Now }上传完成。");

                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
            }
        }
    }
}
